package com.blue.fish.tiny.parser;

import com.blue.fish.tiny.parser.util.PeekTokenIterator;
import com.blue.fish.tiny.lexer.Token;
import com.blue.fish.tiny.parser.ast.ASTNode;
import com.blue.fish.tiny.parser.ast.ASTNodeTypes;
import com.blue.fish.tiny.parser.ast.Expr;
import com.blue.fish.tiny.parser.ast.Scalar;
import com.blue.fish.tiny.parser.util.ParseException;

/**
 * @author QingFan
 * @version 1.0.0
 * @date 2023年02月01日 21:29
 */
public class SimpleParser {

    /**
     * expr -> digit + expr + digit
     * digit -> 0|1|...|9
     */
    public static ASTNode parse(PeekTokenIterator it) throws ParseException {
        Expr expr = new Expr();
        Scalar scalar = new Scalar(expr, it);
        if (!it.hasNext()) {
            return scalar;
        }
        expr.setLexeme(it.peek());
        Token token = it.nextMatch("+");
        expr.setLabel(token.getValue());
        expr.addChild(scalar);
        expr.setType(ASTNodeTypes.BINARY_EXPR);

        ASTNode rightNode = parse(it);
        expr.addChild(rightNode);
        return expr;
    }
}
